package mts.messages;

import mts.constants.EventType;
import mts.constants.MessageType;

public class EventTimeStampMessage extends Message {
	
	public static final int INDEX_EVENT = Message.INDEX_MESSAGE_TYPE + 1;
	public static final int INDEX_CAR = INDEX_EVENT + 1;
	public static final int INDEX_CURRENT_FLOOR = INDEX_CAR + 1;
	public static final int INDEX_TIMESTAMP = INDEX_CURRENT_FLOOR + 1;
	
	public static final int MESSAGE_LENGTH = INDEX_TIMESTAMP + 4;
	
	private EventType event;
	private byte car;
	private long timestamp;
	private byte currentFloor;
	
	public EventType getEvent() {
		return event;
	}

	public byte getCar() {
		return car;
	}

	public long getTimestamp() {
		return timestamp;
	}
	
	public byte getCurrentFloor() {
		return currentFloor;
	}

	private EventTimeStampMessage() {
		super(MessageType.EVENT_MSG);
	}
	
	@Override
	public byte[] serialize() {
		byte[] data = new byte[MESSAGE_LENGTH];
		
		data[Message.INDEX_MESSAGE_TYPE] = getMessageType().getByteValue();
		data[INDEX_EVENT] = getEvent().getByteValue();
		data[INDEX_CAR] = getCar();
		data[INDEX_CURRENT_FLOOR] = getCurrentFloor();
		
		for (int i = 0; i < 4; i++)
		{
			data[INDEX_TIMESTAMP + i] = (byte)((data[INDEX_TIMESTAMP + i] >> (8 * i)) & 0xff);
		}

		return data;
	}
	
	public static EventTimeStampMessage deserialize(byte[] data) {
		
		EventTimeStampMessage message = new EventTimeStampMessage();
		
		message.event = EventType.valueOf(data[INDEX_EVENT]);
		message.car = data[INDEX_CAR];
		message.currentFloor = data[INDEX_CURRENT_FLOOR];
		
		message.timestamp = 0;
		for (int i = 0; i < 4; i++)
		{
			message.timestamp += (data[INDEX_TIMESTAMP + i] & 0xff) << (8 * i);
		}
		
		return message;
	}
	
}
